package xkp.lesson1;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class TestConstroctor {
	public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		//1、获取Class对象
		Class class1 = Class.forName("xkp.lesson1.Person");
		//2、获取构造方法
		//2.1 获取所有非private构造方法
		System.out.println("************获取所有public构造方法************");
		Constructor[] constructors = class1.getConstructors();
		for(Constructor constructor: constructors) {
			System.out.println(constructor);
		}
		
		System.out.println("************获取所有的构造方法包括私有************");
		
		//2.2 获取所有的构造方法包括私有
		constructors = class1.getDeclaredConstructors();
		for(Constructor constructor: constructors) {
			System.out.println(constructor);
		}
		
		//2.3 获取指定的构造方法，技巧是通过参数列表
		System.out.println("************ 获取指定的构造方法************");
		System.out.println("************ 获取无参构造方法************");
		//无参构造的参数为null
		Constructor constructor1 = class1.getConstructor(null);
		//调用无参构造，使用newInstance方式调用构造方法，参数依然为null
		Person person1 = (Person) constructor1.newInstance(null);
		System.out.println(person1);
		System.out.println("************获取带参数的构造方法************");
		Constructor constructor2 = class1.getConstructor(int.class,String.class);
		Person person2 = (Person) constructor2.newInstance(100,"张三");
		System.out.println(person2);
		System.out.println("************可以获取private修饰的构造方法************");
		Constructor constructor3 = class1.getDeclaredConstructor(int.class);
		//设置私有资源允许被访问
		constructor3.setAccessible(true);
		Person person3 = (Person) constructor3.newInstance(100);
		System.out.println(person3);
	}

}
